// pages/function_test/dial_operate/index.ts
import { RCSPOpWatchDial } from "../../../lib/rcsp-impl/rcsp";
// import { File } from "../../../lib/rcsp-protocol/jl-rcsp-op/op-directory-browse";
import { OPWatchDial,OPDirectoryBrowse } from "../../../jl_lib/jl-rcsp-op/jl_op_watch_1.1.0";
import { showActionSheet } from "../../../utils/util";
var RCSPOpWatchDialCallback: OPWatchDial.OperaterEventCallbackWatchDial

Page({

    /**
     * 页面的初始数据
     */
    data: {
        dialList: new Array(),
        customBackgroundList: new Array(),
        useDial: OPDirectoryBrowse.File.prototype
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        RCSPOpWatchDialCallback = {
            onEvent: (_event) => {
                if (_event.type === 'UseDialChange') {
                    const dial = _event.UseDialChange?.dial
                    if (dial) {
                        //@ts-ignore
                        dial.name = dial.getName()
                        this.setData({
                            useDial: dial
                        })
                    }
                } else if (_event.type === 'WatchResourseFileListChange') {
                    const fileList = _event.WatchResourseFileListChange?.fileList
                    if (fileList) {
                        for (let index = 0; index < fileList.length; index++) {
                            const element = fileList[index];
                            //@ts-ignore
                            element.name = element.getName()
                        }
                        this.setData({
                            dialList: this._getWatchFile(fileList),
                            customBackgroundList: this._getCustomBackgroundFile(fileList)
                        })
                    }
                }
            }
        }
        RCSPOpWatchDial?.registerEventCallback(RCSPOpWatchDialCallback)
        RCSPOpWatchDial?.getWatchResourseFileList().then((res) => {
            console.log("获取表盘列表", res);
            for (let index = 0; index < res.length; index++) {
                const element = res[index];
                //@ts-ignore
                element.name = element.getName()
            }
            this.setData({
                dialList: this._getWatchFile(res),
                customBackgroundList: this._getCustomBackgroundFile(res)
            })
            //先进行目录浏览，才可以获取到对应的正在使用文件
            RCSPOpWatchDial?.getUsingDial().then((res) => {
                console.error("当前使用表盘，", res);
                // @ts-ignore
                res.name = res.getName()
                this.setData({
                    useDial: res
                })
            }).catch((error) => {
                console.error("当前使用表盘，失败：", error);
            })
        }).catch((error) => {
            console.error("获取表盘列表,失败：", error);
        })
    },
    onUnload() {
        RCSPOpWatchDial?.unregisterEventCallback(RCSPOpWatchDialCallback)
    },
    /**
    * 点击事件--添加表盘
    */
    clickAddDial(e: WechatMiniprogram.BaseEvent) {
        console.log("添加表盘", e);
        wx.navigateTo({ url: '/pages/function_test/dial_operate/dial_add_dial/index' })
    },
    /**
    * 点击事件--添加表盘背景
    */
    clickAddDialBackground(e: WechatMiniprogram.BaseEvent) {
        console.log("添加表盘背景", e);
        wx.navigateTo({ url: '/pages/function_test/dial_operate/dial_add_background/index' })
    },
    /**
    * 点击事件--表盘操作
    */
    clickDialMoreOperate(e: WechatMiniprogram.BaseEvent) {
        console.log("表盘操作", e);
        const index = e.currentTarget.dataset.index;
        const file: OPDirectoryBrowse.File = this.data.dialList[index]
        //@ts-ignore
        const isUsing = file.name == this.data.useDial.name
        let menu: Array<string>;
        if (isUsing) {
            menu = ["设置自定义表盘背景", "获取表盘版本信息", "获取表盘背景", "删除表盘"]
        } else {
            menu = ["设置为当前使用", "获取表盘版本信息", "获取表盘背景", "删除表盘"]
        }
        return wx.showActionSheet({
            alertText: "表盘:" + file.getName(),
            itemList: menu,
            success: (res) => {
                switch (res.tapIndex) {
                    case 0:
                        if (isUsing) {
                            this._dialOperateSetDialCustomBackground(file)
                        } else {
                            this._dialOperateSetDialIsUsing(file)
                        }
                        break;
                    case 1:
                        this._dialOperateGetDialVersionInfo(file)
                        break;
                    case 2:
                        this._dialOperateGetDialBackground(file)
                        break;
                    case 3:
                        this._dialOperateDeleteDial(file)
                        break;
                }
            }
        })
    },
    /**
     * 表盘操作--设置为当前使用
     */
    _dialOperateSetDialIsUsing(file: OPDirectoryBrowse.File) {
        RCSPOpWatchDial?.setUsingDial(file).then((_res) => {
            wx.showToast({ title: "设置为当前使用成功" })
        }).catch((error) => {
            wx.showToast({ title: "设置为当前使用失败，" + error })
        })
    },
    /**
     * 表盘操作--获取表盘版本信息
     */
    _dialOperateGetDialVersionInfo(file: OPDirectoryBrowse.File) {
        RCSPOpWatchDial?.getDialVersionInfo(file).then((res) => {
            const version = res
            wx.showModal({
                title: "表盘版本信息",
                content: version,
                cancelText: "复制",
                success: (res) => {
                    if (res.cancel) {
                        wx.setClipboardData({
                            data: version,
                            success(_res) { }
                        })
                    }
                }
            })
        }).catch((error) => {
            wx.showToast({ title: "获取表盘版本信息失败," + error })
        })
    },
    /**
     * 表盘操作--获取表盘背景
     */
    _dialOperateGetDialBackground(file: OPDirectoryBrowse.File) {
        RCSPOpWatchDial?.getDialCustomBackground(file).then((res) => {
            const content = res == null ? "无" : res.getName()
            wx.showModal({
                title: "表盘背景-表盘:" + file.getName(),
                content: content,
                showCancel: false,
                success: (_res) => {
                }
            })
        }).catch((error) => {
            wx.showToast({ title: "获取表盘背景失败," + error })
        })
    },
    /**
     * 表盘操作--设置自定义背景(仅限当前使用表盘)
     */
    _dialOperateSetDialCustomBackground(file: OPDirectoryBrowse.File) {
        if (this.data.customBackgroundList.length == 0) {
            return wx.showToast({ title: "表盘背景列表为空，请先添加表盘背景" })
        }
        RCSPOpWatchDial?.getDialCustomBackground(file).then((dialBackground) => {
            const menu = new Array<string>()
            menu.push("恢复默认背景")
            for (let index = 0; index < this.data.customBackgroundList.length; index++) {
                const element = this.data.customBackgroundList[index];
                menu.push(element.getName())
            }
            const config = {
                alertText: "当前表盘背景:" + dialBackground?.getName(),
                itemList: menu,
                success: (res:any) => {
                    let backgroundFile: any
                    if (res.tapIndex ==0) {
                        backgroundFile = undefined
                    } else {
                        backgroundFile = this.data.customBackgroundList[res.tapIndex-1]
                    }
                    if (!backgroundFile || backgroundFile.getName() != dialBackground?.getName()) {
                        RCSPOpWatchDial?.setDialCustomBackground(backgroundFile).then((_res) => {
                            if (backgroundFile) {
                                wx.showToast({ title: "设置自定义背景成功" })
                            } else {
                                wx.showToast({ title: "恢复默认背景成功" })
                            }
                        }).catch((error) => {
                            wx.showToast({ title: "设置自定义背景失败," + error })
                        })
                    }
                }
            }
            showActionSheet(config)
        }).catch((error) => {
            wx.showToast({ title: "获取当前表盘背景失败," + error })
        })
        return
    },
    /**
     * 表盘操作--删除表盘
     */
    _dialOperateDeleteDial(file: OPDirectoryBrowse.File) {
        wx.showModal({
            title: "删除表盘:" + file.getName(),
            content: "确定要删除表盘文件?",
            confirmText: "删除",
            cancelText: "取消",
            success: (res) => {
                if (res.confirm) {
                    RCSPOpWatchDial?.deleteDial(file).then((_res) => {
                        wx.showToast({ title: "删除表盘成功" })
                    }).catch((error) => {
                        wx.showToast({ title: "删除表盘失败," + error })
                    })
                } else if (res.cancel) {
                }
            }
        })
    },
    /**
    * 点击事件--自定义表盘背景操作
    */
    clickDialBackground(e: WechatMiniprogram.BaseEvent) {
        console.log(" 表盘背景操作:", e);
        const index = e.currentTarget.dataset.index;
        const file: OPDirectoryBrowse.File = this.data.customBackgroundList[index]
        return wx.showActionSheet({
            alertText: "表盘背景:" + file.getName(),
            itemList: ["删除表盘背景"],
            success: (res) => {
                switch (res.tapIndex) {
                    case 0:
                        this._dialOperateDeleteDialBackground(file)
                        break;
                }
            }
        })
    },
    /**
     * 表盘操作--删除表盘背景
     */
    _dialOperateDeleteDialBackground(file: OPDirectoryBrowse.File) {
        wx.showModal({
            title: "删除表盘背景:" + file.getName(),
            content: "确定要删除表盘背景?",
            confirmText: "删除",
            cancelText: "取消",
            success: (res) => {
                if (res.confirm) {
                    RCSPOpWatchDial?.deleteDialCustomBackground(file).then((_res) => {
                        wx.showToast({ title: "删除表盘背景成功" })
                    }).catch((error) => {
                        wx.showToast({ title: "删除表盘背景失败," + error })
                    })
                } else if (res.cancel) {
                }
            }
        })
    },
    /**
     * 获取表盘文件
     */
    _getWatchFile(fileList: OPDirectoryBrowse.File[]) {
        const filt = "WATCH"
        const result = new Array<OPDirectoryBrowse.File>()
        for (let index = 0; index < fileList.length; index++) {
            const element = fileList[index];
            if (element.getName()?.toUpperCase().includes(filt)) {
                result.push(element)
            }
        }
        return result
    },
    /**
    * 获取自定义背景文件
    */
    _getCustomBackgroundFile(fileList: OPDirectoryBrowse.File[]) {
        const filt = "BGP"
        const result = new Array<OPDirectoryBrowse.File>()
        for (let index = 0; index < fileList.length; index++) {
            const element = fileList[index];
            if (element.getName()?.toUpperCase().includes(filt)) {
                result.push(element)
            }
        }
        return result
    }
})